import React from 'react';
import { Route, Redirect, RouteProps } from 'react-router-dom';
import { hasToken } from '@/utils/storage';

// extends RouteProps继承原有的属性支持,exact等属性
export interface AuthRouteProps extends RouteProps {
  component: React.FC<any>;
  path: string;
}
export type LocationStateType = {
  from: string;
};
/* 路由鉴权(导航守卫)组件 */
export function AuthRoute(props: AuthRouteProps) {
  const { component: Comp, path, ...restProps } = props;
  return (
    <Route
      // {...restProps}给Route透传回去
      {...restProps}
      path={path}
      render={(_props) => {
        if (hasToken()) return <Comp {..._props} />;
        // return <Redirect to="/login" />;
        // 第二种写法(重新登录时,跳回之前页)
        // to属性接收对象 pathname要跳转的路由,state传参
        return (
          <Redirect
            to={{
              pathname: '/login',
              state: { from: path } as LocationStateType,
            }}
          />
        );
      }}
    ></Route>
  );
}
